<template>
  <!-- 盒子整体 -->
  <div class="bigbox">
    <!-- 左侧盒子树结构 -->
    <div class="leftbox">
      <div class="select">
        <span class="text">能源类型/介质</span>
        <span class="span">
          <el-select v-model="model" placeholder="请选择" size="small" @change="changetype">
            <el-option
            class="option"
              v-for="item in options"
              :key="item.value"
              :label="item.name"
              :value="item.code">
            </el-option>
          </el-select>
        </span>
      </div>
      <div style="margin-top:10px;">
        <template>
              <el-autocomplete
              class="inline-input"
              v-model="filterText"
              size="small"
              style="margin-bottom: 10px;width:100%"
              :fetch-suggestions="querySearch"
              placeholder="输入关键字进行过滤"
              :trigger-on-focus="true"
              value-key="name"
              :debounce='300'
              @select="handleSelect"
            ></el-autocomplete>
          </template>
      </div>
      <div class="treebox">
        <!-- 树状图区域结构 -->
        <el-tree
          :props="props"
          :load="loadNode"
          node-key="id"
          accordion
          :highlight-current="true"
          :default-expanded-keys="array"
          lazy
          @node-click="handleNodeClick"
          ref="tree"
          >
          <template slot-scope="{ node, data }">
            <span :style="{ fontSize:'14px',color:'#606266'}">
              <img :src="'data:image/png;base64,' + data.iconBase64" style="  width: 16px; height: 16px; margin-right: 5px; vertical-align: bottom;"/>
              {{ node.label }}</span>
          </template>
        </el-tree>
      </div>
    </div>
    <!-- 右侧盒子主体 -->
    <div class="rightbox">
      <!-- 右侧盒子头部搜索栏 -->
      <div class="sousuobox">
        <div>
          <el-radio-group v-model="radio3" size="small">
            <el-radio-button label="2">月</el-radio-button>
            <el-radio-button label="3">年</el-radio-button>
          </el-radio-group>
          <span>
            <el-date-picker v-if="radio3=='2'" v-model="value2" type="month" value-format="yyyy-MM" placeholder="选择月" size="small"></el-date-picker>
            <el-date-picker v-else v-model="value3" type="year" value-format="yyyy" placeholder="选择年" size="small"></el-date-picker>
          </span>
        </div>
        <div>
          <el-button size="small">重 置</el-button>
          <el-button size="small" type="primary" @click="submit">查 询</el-button>
        </div>
      </div>
      <!-- 右侧盒子主体 -->
      <div class="bodybox">
        <div class="bingtuech">
          <!-- <transition name="el-fade-in" mode="out-in"> -->
            <div v-show="model=='01'" class="bingtu" >
              <div>电费组成</div>
              <div ref="pieech" style="height: 95%;"></div>
            </div>
          <!-- </transition> -->
          <!-- <transition name="el-fade-in" mode="out-in"> -->
            <div class="zexian">
              <div class="export">
                <span>平均{{this.model=='01'?'电':'水'}}价</span>
              </div>
              <div class="lineech" ref="lineech"></div>
            </div>
          <!-- </transition> -->
        </div>
        <div class="tabandzhu">
          <!-- <TableEchart :barlist="barlist"></TableEchart> -->
          <div class="bigboxss">
            <div class="title">
              <span>{{this.model=='01'?'电':'水'}}费趋势</span>
              <span style="display: flex;align-items: center;">
                <i :style="{color:isshow==='echart'?'#007cee':''}" @click="addechart" class="iconfont icon-zhuzhuangtutubiao"></i>
                <i :style="{color:isshow==='table'?'#007cee':''}" @click="addtable" class="iconfont icon-biaoge"></i>
                <el-button style="margin-left: 10px;" size="small" type="primary" @click="daochu">导 出</el-button>
              </span>
            </div>
            <div class="bodytabech">
              <div v-show="isshow=='echart'" class="table" ref="echartsssss"></div>
              <div class="table" v-show="isshow=='table'">
                <TableColumn ref="tabledata"
                :tableData="tableData" 
                :tableConfig="tableConfig" >
                </TableColumn>
                <!-- 底部分页 -->
                <div class="fenye">
                  <el-pagination
                    background
                    layout="prev, pager, next"
                    :current-page.sync="page.pageNo"
                    :page-size="10"
                    @current-change="gettablelist"
                    :total="+totalCount">
                   </el-pagination>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import elementResizeDetectorMaker from "element-resize-detector";
import TableColumn from '@/components/Table/index.vue'
import * as echarts from 'echarts';
import {getgenjiedianapi,getzijidianapi,getnengyuantypeapi} from '@/api/energy-consumption/Basic-information/gateway'
import { getKeywordListApi } from '@/api/Ledger3'
import TableEchart from './tableandechart.vue'
import { getpieechartapi, getlineechartapi, getbarechartapi, gettabledataapi } from '@/api/energy-consumption/Basic-analysis/EnergyCosts'
import {exportexcel} from '@/utils/excel'
export default {
  name: 'CallPoliceIndex',
  components: {
    TableEchart,
    TableColumn
  },
  data() {
    return {
      value3:'',
      value2:'',
      radio3:'2',
      filterText: '',
      props: {
        label: 'name',
        children: 'children',
        isLeaf: 'leaf'
      },
      array: [],
      options: [],
      model: '',
      treevalue: {},
      isshow:'echart',
      tableData:[],
      tableConfig: [],
      totalCount: '',
      page: {
        pageNo: 0,
        pageSize:10
      }
    };
  },

  async mounted() {
    // 获取能源介质
    const jiezhi = await getnengyuantypeapi()
    this.options = jiezhi.data.list
    this.model=jiezhi.data.list[0].code
    this.gettime()
    this.getlineech([])
    this.getbarechart([])
    setTimeout(()=>this.getpieechart({}),100)
  },

  methods: {
    // 树节点选中
    handleNodeClick(val) {
      this.treevalue = val
      this.submit()
    },
    // 类型选择
    changetype(val) {
      this.submit()
      if (val == '01') {
        this.isshow='echart'
      } else {
        this.isshow='table'
      }
    },
    // 查询
    async submit() {
      if(!this.treevalue.id) return this.$message.warning('请先选择设备')
      if (this.model == '01') {
        const res = await getbarechartapi({ classId: this.treevalue.id, dateString: this.radio3 == '2' ? this.value2 : this.value3, dateType: this.radio3 })
        this.getbarechart(res.data.list)
        const {data:{entity}} = await getpieechartapi({ classId: this.treevalue.id, dateString: this.radio3 == '2' ? this.value2 : this.value3, dateType: this.radio3 })
        this.getpieechart(entity)
      }
      const {data:{list}}=await getlineechartapi({ classId: this.treevalue.id, dateString: this.radio3 == '2' ? this.value2 : this.value3, dateType: this.radio3,energyType:this.model })
      this.getlineech(list)
      this.gettablelist()
    },
    // 获取列表数据
    async gettablelist() {
      this.$refs.tabledata.loading=true
      const {data:{list,totalCount}} = await gettabledataapi({
        classId: this.treevalue.id,name:this.treevalue.name,pageNo: this.page.pageNo - 1, pageSize: this.page.pageSize,
        dateString: this.radio3 == '2' ? this.value2 : this.value3, dateType: this.radio3, energyType: this.model
      })
      this.tableData = list
      this.totalCount = totalCount
      if (this.model == '01') {
        this.tableConfig=[
          { label: '日期', prop: 'dateTime',  },
          { label: '用能单元名称', prop: 'unitName',  },
          { label: '尖电量(kWh)', prop: 'sharpValue',},
          { label: '尖电费(元)', prop: 'sharpAmount',},
          { label: '峰电量(kWh)', prop: 'peakValue',},
          { label: '峰电费(元)', prop: 'peakAmount', },
          { label: '平电量(kWh)', prop: 'flatValue',},
          { label: '平电费(元)', prop: 'flatAmount', },
          { label: '谷电量(kWh)', prop: 'valleyValue',},
          { label: '谷电费(元)', prop: 'valleyAmount',},
          { label: '总电量(kWh)', prop: 'usageValue',},
          { label: '总电费(元)', prop: 'totalAmount', },
          { label: '平均电价(元/kWh)', prop: 'unitPrice',},
        ]
      } else {
        this.tableConfig=[
          { label: '日期', prop: 'dateTime',  },
          { label: '用能单元名称', prop: 'unitName',  },
          { label: '总水量(m³)', prop: 'usageValue',},
          { label: '总水费(元)', prop: 'totalAmount', },
          { label: '平均水价(元/m³)', prop: 'unitPrice',},
        ]
      }
      this.$refs.tabledata.loading=false
    },
    //  导出
    daochu() {
      exportexcel('ecm-microservice-biz/ecm/basic/statistics/cost/exportExcel', {
        classId: this.treevalue.id,name:this.treevalue.name,pageNo: this.page.pageNo - 1, pageSize: this.page.pageSize,
        dateString: this.radio3 == '2' ? this.value2 : this.value3, dateType: this.radio3, energyType: this.model
      },'能源成本分析')
    }, 
   // 树节点搜索
   async querySearch (queryString, cb) {
       setTimeout(async () => {
        const res = await getKeywordListApi({name:queryString})
      const restaurants = res.data.list
      cb(restaurants)
      },500)
      // 调用 callback 返回建议列表的数据
    },
    // 搜索选择
    handleSelect (item) {
      const newarr=item.pathId.split(',')
      for (let i = 0;i<newarr.length;i++) {
        if (newarr[i]) {
          this.array.push(newarr[i])
        }
      }
      function getgaoliang(that) {
        let node = that.$refs.tree.getNode(item);
        if (node) {
          that.handleNodeClick(node.data)
          that.$refs.tree.setCurrentKey(String(item.id));
        } else {
          setTimeout(() => {
            getgaoliang(that)
          }, 500);
        }
        }
      getgaoliang(this)
    },
    // 树结构懒加载
    async loadNode (node, resolve) {
      const res = await getgenjiedianapi({ treeModel: 'ENERGY_SET_TREE' })
      const ress = await getzijidianapi(res.data.list[0])
      if (node.level === 0) {
        this.handleNodeClick(ress.data.list[0])
        return resolve(ress.data.list)
      } else if (node.level >= 1) {
        const ress = await getzijidianapi(node.data)
        return resolve(ress.data.list)
      }
    },
    // 获取饼图
    getpieechart(obj) {
      var chartDom = this.$refs.pieech
      var myChart = echarts.init(chartDom);
      const valuedata=[
              { value: obj.sharpAmount, name: '尖' },
              { value: obj.peakAmount, name: '峰' },
              { value: obj.flatAmount, name: '平' },
              { value: obj.valleyAmount, name: '谷' }
            ]
      var option;
      option = {
        tooltip: {
          trigger: 'item'
        },
        legend: {
          itemGap:20,
          icon: 'circle',
          orient: 'horizontal',
          left: 'center',
          top:20
        },
        series: [
          {
            name: '',
            type: 'pie',
            center: ['50%', '55%'],
            radius: '60%',
            data: valuedata,
                      itemStyle: {
                    normal: {
                      color: function (colors) {
                        var colorList = ['#1890FF','#66CBFF ','#23CFC4 ','#F6BF24 '];
                        return colorList[colors.dataIndex];
                      }
                    },
                  },
                  labelLine: {
                    show: true,
                    length: 20,
                    length2: 40,
                    smooth: true
                  },
                  label: {
                    normal: {
                      formatter:'{b}:  {d}',
                      rich: {
                        c: {
                          color: "inherit",
                          fontSize: 20,
                          fontWeight: "bold",
                          lineHeight: 5,
                        },
                        b: {
                          fontSize: 15,
                          height: 40,
                        },
                      },
                    },
                  },
          }
        ]
      };
      myChart.clear();
      option && myChart.setOption(option);
      window.addEventListener("resize", () => {
        myChart.resize();
      });
    },
    // 获取折线图
    getlineech(list) {
      var chartDom = this.$refs.lineech
      var myChart = echarts.init(chartDom);
      var option;
      console.log(list);
      const timePoints = list[0]?.datalist.map(ele => ele.timeReading)
      const bararr=[]
      const linearr = []
      list.map(ele => {
        if (ele.name == '总费用') {
           ele.datalist.map(ele =>bararr.push( ele.valueReading))
        }else if(ele.name == '平均价格'){
           ele.datalist.map(ele =>linearr.push( ele.valueReading))
        }
      })
      option = {
        tooltip: {
          trigger: 'axis'
        },
        legend: {

        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '0%',
          containLabel: true
        },
        calculable: true,
        xAxis: {
          type: 'category',
          // boundaryGap: false,
          data: timePoints
        },
        yAxis:[
          {
            type: 'value',
            name: '元',
            axisLabel: {
                formatter: '{value}'
            }
          },
          {
            type: 'value',
            name: '元',
            axisLabel: {
                formatter: '{value}'
            }
          }
      ],
        series: [
      {
         name: '总费用',
         type: 'bar',
         data: bararr
      },
      {
         name: '平均价格',
         type: 'line',
         yAxisIndex: 1,
         data:linearr
      }
   ]
      };
      myChart.clear();
      option && myChart.setOption(option);
      window.addEventListener("resize", () => {
        myChart.resize();
      });
            // 根据当前容器的尺寸变化而让图表也跟着变化
            let changeSize = elementResizeDetectorMaker()
            let _this = this
            changeSize.listenTo(chartDom,() => {  //chartDom为之前获取到的容器名
                _this.$nextTick(() => {
                    myChart.resize()
                })
            })
    },
    // 获取当前时间戳
    gettime() {
      const date = new Date()
      const year = date.getFullYear() // 年
      const mon = date.getMonth() + 1 // 月
      const month =mon<10?'0'+mon:mon
      const day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate() //日
      this.value3 = year.toString()
      this.value2 = year + '-' + month
    },
    addtable() {
      this.isshow = 'table'
    },
    addechart() {
      if (this.model == '01') {
        this.isshow = 'echart'
      }
    },
    // 获取堆叠柱状图
    getbarechart(list) {
      var chartDom = this.$refs.echartsssss
      var myChart = echarts.init(chartDom);
      var option;
      const timePoints = list[0]?.datalist.map(ele => ele.timeReading)
      const series = list.map(ele => {
        return {
            name:ele.name,
            data: ele.datalist.map(ele=>ele.valueReading),
            type: 'bar',
            stack: 'total',
            emphasis: {
              focus: 'series'
            },
            animationDelay: function (idx) {
              return idx * 50 + 1000;
            }
          }
      })
      option = {
        tooltip: {
          trigger: 'axis',
        },
        legend: {},
        grid: {
          left: '1%',
          right: '1%',
          bottom: '1%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: timePoints
        },
        yAxis: {
          name:'kWh',
          type: 'value',
        },
        series: series,
        animationEasing: 'elasticOut',
        animationDuration: 2000,
        // barWidth: 60
      };
      myChart.clear();
      option && myChart.setOption(option);
      window.addEventListener("resize", () => {
        myChart.resize();
      });
                  // 根据当前容器的尺寸变化而让图表也跟着变化
                  let changeSize = elementResizeDetectorMaker()
            let _this = this
            changeSize.listenTo(chartDom,() => {  //chartDom为之前获取到的容器名
                _this.$nextTick(() => {
                    myChart.resize()
                })
            })
    }
  },
  watch: {
    filterText (newValue) {
      this.filterText = newValue.replace(/^\[(.*?)\]/, '').replace(/\((.*?)\)$/, '')
    },
  }
};
</script>

<style scoped>
.option{
  padding-left: 10px;
}
.bigbox{
  height: 100%;
  padding: 10px;
  display: flex;
  .leftbox{
    width: 300px;
    padding: 15px;
    background-color: #fff;
    height: 100%;
    margin-right: 10px;
    .select{
      display: flex;
      align-items: center;
      .text{
        font-size: 14px;
        margin-right: 5px;
      }
      .span{
        display: inline-block;
        flex:1;
      }
    }

  }
  .rightbox{
    width: calc(100% - 310px);
    .sousuobox{
      height: 80px;
      padding: 0 20px;
      line-height: 80px;
      background-color: #fff;
      margin-bottom: 10px;
      display: flex;
      justify-content: space-between;
      span{
        margin-left: 20px;
      }
    }
    .bodybox{
      height: calc(100% - 90px);
      .bingtuech{
        height: calc(50% - 5px);
        margin-bottom: 10px;
        display: flex;
        .bingtu{
          width: 40%;
          background-color: #fff;
          margin-right: 10px;
          /* transition:  1s; */
          padding: 20px;
        }
        .zexian{
          flex: 1;
          background-color: #fff;
          padding: 20px;
          transition: width 0.5s, height 0.5s, ;
          .export{
            display: flex;
            justify-content: space-between;
          }
          .lineech{
            height: 90%;
          }
        }
      }
      .tabandzhu{
        height: calc(50% - 5px);
        background-color: #fff;
        .bigboxss{
          height: 100%;
          padding: 20px;
          .title{
            display: flex;
            justify-content: space-between;
            i{
              margin-left: 10px;
              cursor: pointer;
              /* font-size: 20px; */
            }
            i:hover{
              color: #2194ff;
            }
          }
          .bodytabech{
            height: 95%;
            .table{
              height: 95%;
              .fenye{
                text-align: right;
              }
            }
          }
        }
      }
    }
  }
}
</style>